package com.iot.ht.controller.htfile;


import com.iot.core.annotation.Auth;
import com.iot.core.annotation.Log;
import com.iot.core.data.entity.HtActionLog;
import com.iot.core.data.service.IHtActionLogService;
import com.iot.core.enums.AuthType;
import com.iot.core.exception.MyException;
import com.iot.core.manager.id.HtIdManager;
import com.iot.core.springboot.properties.FileProperty;
import com.iot.core.util.ContentTypeUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/htfile")
@Tag(name = "文件上传", description = "文件上传")

public class HtFileController {
    @Autowired
    FileProperty fileProperty;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    HttpServletRequest req;
    @Autowired
    HttpServletResponse res;

    @Autowired
    IHtActionLogService iHtActionLogService;
    @RequestMapping("/index")
    public  String index(){
        var m=new HtActionLog();
        iHtActionLogService.saveLogAsync(m);
        log.info("abcd");
        return "abcd";
    }
    private static final String TBHTFile = "HTFile";
    @Auth(authType = AuthType.Login)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @PostMapping("/up")
    @Operation(summary = "上传文件", description = "")
    public HtFileDto Up(@RequestParam(name ="file") MultipartFile  file) throws IOException {
       var serverurlprev=fileProperty.getFixHttpPrev();
       if("".equals(serverurlprev)){
           serverurlprev=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort();
       }
       if(file==null){
           throw  new MyException("没有上传文件");
       }
        if(file.getSize()>fileProperty.getMaxFileSize() ){
            throw  new MyException("文件太大");
        }
        var m=new HtFileDto();
        int fileSize=(int)(file.getSize());
        m.setId(HtIdManager.getInstance().nextLong());
        m.setName(file.getOriginalFilename());

        var mdb=new MongoHtFileDto();
        mdb.setId(m.getId());
        mdb.setName(m.getName());
        mdb.setMemo(m.getMemo());
        mdb.setSize(file.getSize());
        mdb.setGid(HtIdManager.getInstance().nextGuid().toString() );

        if(mdb.getSize()<12*1024*1024){
            mdb.setData(new byte[ fileSize   ]);
            file.getInputStream().read(mdb.getData(),0,fileSize );
        }else{
            GridFSBucket bucket = GridFSBuckets.create(mongoTemplate.getDb());
            var oid=bucket.uploadFromStream(m.getName(), file.getInputStream());
            mdb.setFileId(oid.toString() );
        }
        var m2=mongoTemplate.insert(mdb,TBHTFile);
        m.setUrl( serverurlprev+"/htfile/show?id="+mdb.getId().toString()  );
        return m;
    }

    @Auth(authType = AuthType.None)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @GetMapping("/down")
    @Operation(summary = "下载文件", description = "")
    public  void Down(@RequestParam Long id) throws IOException {
        var mdb=mongoTemplate.findById(id, MongoHtFileDto.class,"HTFile");

        res.setContentType("application/x-download");
        res.setHeader( "Content-Disposition", String.format("attachment; filename=%s",mdb.getName()) );

        setRes(mdb);
    }

    @Auth(authType = AuthType.None)
    @Log(logNeed = false,logTemplete ="",logPin = true,logPout = true)
    @GetMapping("/show")
    @Operation(summary = "显示文件", description = "")
    public  void Show(@RequestParam Long id) throws IOException {
        var mdb=mongoTemplate.findById(id, MongoHtFileDto.class,"HTFile");

        var ContentType= ContentTypeUtil.getMimeType(mdb.getName() );
        //"application/x-download"
        res.setContentType(ContentType);
//        res.setHeader("Pragma", "no-cache");
//        res.setHeader("Cache-Control", "no-cache");
        setRes(mdb);
    }
    private void setRes(MongoHtFileDto mdb) throws IOException {
        if("".equals(mdb.getFileId())){
            var data=mdb.getData();

            res.getOutputStream().write(data);
        }
        else{
            GridFSBucket bucket = GridFSBuckets.create(mongoTemplate.getDb());
            bucket.downloadToStream(new ObjectId(mdb.getFileId()), res.getOutputStream() );

        }
    }
}
